using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Common.Tools
{
    public static class SerializeHelper
    {
        public static byte[] SerializeToBinary(object obj)
        {
            // 将对象序列化为 JSON 字符串  
            string jsonString = JsonConvert.SerializeObject(obj);

            // 将 JSON 字符串转换为字节数组  
            byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonString);

            return data;
        }

        public static T DeserializeFromBinary<T>(byte[] data) where T : class
        {
            // 将字节数组转换为 JSON 字符串  
            string jsonString = System.Text.Encoding.UTF8.GetString(data);

            // 将 JSON 字符串反序列化为对象  
            T obj = JsonConvert.DeserializeObject<T>(jsonString);

            // 检查反序列化结果是否为 null  
            if (obj == null)
            {
                throw new InvalidOperationException("反序列化结果为 null。");
            }

            return obj;
        }

        public static object DeserializeFromBinary(byte[] data, Type type)
        {
            string jsonString = Encoding.UTF8.GetString(data);
            object? obj = JsonConvert.DeserializeObject(jsonString, type);

            // 检查反序列化结果是否为 null  
            if (obj == null)
            {
                throw new InvalidOperationException("反序列化结果为 null。");
            }

            return obj;
        }
    }

    // public class SerializeHelper
    // {
    //     /// <summary>
    //     /// 讲二进制数据反序列化
    //     /// </summary>
    //     /// <param name="data"></param>
    //     /// <returns></returns>
    //     /// <exception cref="System.NotImplementedException"></exception>
    //     public static object DeserializeWithBinary(byte[] data)
    //     {
    //         MemoryStream stream = new MemoryStream();
    //         stream.Write(data, 0, data.Length);
    //         stream.Position = 0;
    //         BinaryFormatter bf = new BinaryFormatter();
    //         object obj = bf.Deserialize(stream);

    //         stream.Close();
    //         return obj;
    //     }

    //     /// <summary>
    //     /// 序列化对象
    //     /// </summary>
    //     /// <param name="obj"></param>
    //     /// <returns></returns>
    //     public static byte[] SerializeToBinary(object obj)
    //     {
    //         MemoryStream stream = new MemoryStream();
    //         BinaryFormatter bf = new BinaryFormatter();
    //         bf.Serialize(stream, obj);

    //         byte[] data = stream.ToArray();
    //         stream.Close();

    //         return data;
    //     }
    // }
}
